package org.zjt.spring.test.demo.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/**
 * Description: bean 注册器
 *
 * @author juntao.zhang
 * Date: 2018-05-22 上午10:58
 * @see
 */
@Configuration
public class ConfigurationBeanRegistrar implements ApplicationContextAware {

    private DefaultListableBeanFactory defaultListableBeanFactory;

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        this.defaultListableBeanFactory = DefaultListableBeanFactory.class.cast(applicationContext.getAutowireCapableBeanFactory());
    }


    /**
     * 注册一个BeanDefinition
     * @param beanDefinition
     * @param name
     * @return
     */
    public BeanMetaData registerBeanDefinition(AbstractBeanDefinition beanDefinition, String name) {
        defaultListableBeanFactory.registerBeanDefinition(name, beanDefinition);
        return BeanMetaData.builder().name(name).type(beanDefinition.getBeanClass()).build();
    }

    /**
     * 得到bean实例
     * @param beanTypeMetaData
     * @return
     */
    public Object getInstance(BeanMetaData beanTypeMetaData){
         return applicationContext.getBean(beanTypeMetaData.getName(), beanTypeMetaData.getType());
    }

}
